<!DOCTYPE html>
<html>
<head>
<title>Global Index Watch</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet" media="screen">
<style>
	body {
		padding: 5px;
	}
	.separator {
		margin-left: 5px;
	}
</style>
</head>
<body>
	
	<!--  
	<div id="adContent2" style="height:60px">
		<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
		GIW_Module
		<ins class="adsbygoogle"
		     style="display:inline-block;width:468px;height:60px"
		     data-ad-client="ca-pub-9983113299815649"
		     data-ad-slot="7631094754"></ins>
		<script>
		(adsbygoogle = window.adsbygoogle || []).push({});
		</script>
		<script type="text/javascript">
		  var _gaq = _gaq || [];
		  _gaq.push(['_setAccount', 'UA-1214589-10']);
		  _gaq.push(['_trackPageview']);
		
		  (function() {
		    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
		    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
		    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
		  })();
		</script>
	</div>
	-->
	<a href="#settingsModal" class="btn btn-small pull-right" data-toggle="modal" id="settingsloadbtn" style="margin-left:5px"><i class="icon-cog"></i> Settings</a>
	<a href="http://udaysasi-gadgets.googlecode.com/svn/trunk/globalIndexWatch.html" class="btn btn-small pull-right" target="newwin" id="fullscreen"><i class="icon-fullscreen"></i> FullScreen</a>
	<div class="clearfix"></div>
	<div class="clearfix alert hide" id="message" style="margin-bottom:0px;padding:2px;">
		<small>Temporary fix has been put in place for Internet Explorer users. Permanent fix coming soon.</small>  
	</div>  
	<div id="contentData" class="contentData clearfix">
		<table class="table table-condensed table-striped">
			<tbody>
				<tr>
					<td colspan="5" style="text-align:center">Loading Global Market Indices.. Please wait..</td>
				</tr>
			</tbody>
		</table>
	</div>
	
	<div id="adContent" style="height:60px">
		<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
		<!-- GIW_Module -->
		<ins class="adsbygoogle"
		     style="display:inline-block;width:468px;height:60px"
		     data-ad-client="ca-pub-9983113299815649"
		     data-ad-slot="7631094754"></ins>
		<script>
		(adsbygoogle = window.adsbygoogle || []).push({});
		</script>
		<script type="text/javascript">
		  var _gaq = _gaq || [];
		  _gaq.push(['_setAccount', 'UA-1214589-10']);
		  _gaq.push(['_trackPageview']);
		
		  (function() {
		    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
		    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
		    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
		  })();
		</script>
				
	</div>
	
	<form class="form-inline">
		<a class="separator" href="#" id="strengthbtn">Strength</a>
		<a class="separator" href="http://udaysasi-gadgets.googlecode.com/svn/trunk/globalIndexWatchHelp.html"  target="globalindexwatchhelp">Help</a>
		<a class="separator" href="mailto:udaysasi+feedback@gmail.com" target="emailpage">Feedback</a>
	</form>
	<table width="99%" id="strengthContent" style="display:none">
		<tbody>
		<tr>
			<td style="width:100%">
				<table style="align:center" border="0" cellpadding="0" cellspacing="0" width="100%">
					<tbody>
					<tr style="height:15px">
						<td id="n59" style="background-color: #992020;width:0%" title=""></td>
						<td id="n25" style="background-color: #CC4949;width:0%" title=""></td>
						<td id="n02" style="background-color: #FF8383;width:0%" title=""></td>
						<td id="p02" style="background-color: #83FF83;width:0%" title=""></td>
						<td id="p25" style="background-color: #49CC49;width:0%" title=""></td>
						<td id="p59" style="background-color: #209920;width:0%" title=""></td>
					</tr>
					</tbody>
				</table>
			</td>
		</tr>
		</tbody>
	</table>
	<div class="muted text-center"><small>(Data and Charts provided by Yahoo! Finance)</small></div>
	
	<!-- Settings Modal -->
	<div id="settingsModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="settingsModalLabel" aria-hidden="true">
		<div class="modal-header">
			<button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
			<h3 id="settingsModalLabel">Settings</h3>
		</div>
		<div class="modal-body">
			<form class="form-horizontal" onsubmit="return false;">
			  <div class="control-group">
			    <label class="control-label" for="inputRegion">Show Market Indices</label>
			    <div class="controls" id="inputRegion">
			      <select>
					  <option value="1">Americas</option>
					  <option value="2">Europe</option>
					  <option value="3">Asia Pacific</option>
					  <option value="-1">All</option>
					</select>
			    </div>
			  </div>
			  <div class="control-group">
			    <label class="control-label" for="inputHidecols">Hide Columns</label>
			    <div class="controls" id="inputHidecols">
			      <select>
					  <option value="1">Change</option>
					  <option value="2">Percent Change</option>
					  <option value="-1">None</option>
					</select>
			    </div>
			  </div>
			  <div class="control-group">
			    <label class="control-label" for="inputShowCharts">Show Charts</label>
			    <div class="controls" id="inputShowCharts">
			      <select>
					  	<option value="0">None</option>
						<option value="1">1 day</option>
						<option value="5">5 day</option>
						<option value="90">3 month</option>
						<option value="180">6 month</option>
						<option value="365">1 year</option>
					</select>
			    </div>
			  </div>
			</form>
		</div>
		<div class="modal-footer">
			<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
			<button class="btn btn-primary" data-dismiss="modal" id="settingssavebtn">Save changes</button>
		</div>
	</div>
	
	<script src="http://code.jquery.com/jquery.js"></script>
	<script src="bootstrap/js/jquery.cookie.js"></script>
	<script src="bootstrap/js/bootstrap.min.js"></script>
	<script src="bootstrap/js/json2.js"></script>
	<script src="bootstrap/js/storage.js"></script>
	<script type="text/javascript" src="apigee.min.js"></script>
	
	<script type="text/javascript">
		
		var userId = null;
		var userPrefs = null;

		var localStore = {
			setItem : null,
			getItem : null
		};
	
	    var searchkey = self.location.search;
		if(searchkey!='') {
			searchkey = searchkey.substring(1);
			var pairs = searchkey.split("=");
			if(pairs[0]=="subscriptionid") {
				userId = pairs[1];
				userId = userId.replace("@","");
			}
		}
		
		//Redirect user to the new Github URL
		var url = self.location.href;
		url = url.replace('http://udaysasi-gadgets.googlecode.com/svn/trunk', 'http://udaysasigadgets.github.io');
		self.location.href=url;
		
		var client = new Usergrid.Client({
	        orgName:'perfectpluto',
	        appName:'sandbox'
	    });
	    
	    function getUserPrefs(callback) {
	    	var prefTimeout = window.setTimeout(callback, 10000);
	    	var opts = {
	        	'type':'ighgiwprefs',
	        	'name':userId,
	        	getOnExist:true,
	        	'gadget':'giw'
	        };
	       	client.createEntity(opts, function(err, pref) {
	        	if(err) {
	        		console.log("Error creating preferences object");
	        		/*Temporary Fix for IE users*/
	        		userId = null;
	        		try {
	    				var p = window.localStorage;
	    				localStore.setItem = function(i,v) {
	    					console.log("setting to localStorage : "+i+"="+v);
	    					localStorage.setItem(i,v);
	    				}
	    				localStore.getItem = function(i) {
	    					console.log("reading from localStorage : "+i);
	    					return localStorage.getItem(i);
	    				}
	    			} catch(e) {
	    				console.log("seems to be inside an iframe, Using cookie instead..");
	    				localStore.setItem = function(i,v) {
	    					console.log("setting to cookie : "+i+"="+v);
	    					$.cookie(i, v);
	    				}
	    				localStore.getItem = function(i) {
	    					console.log("reading from cookie : "+i);
	    					return $.cookie(i);
	    				}
	    			}
	    			//Inform the user
	    			$("#message").removeClass("hide");
	    			callback();
	    			/*Temporary Fix for IE users*/
	        	} else {
	        		console.log("Preferences object : "+pref.get('uuid'));
	        		userPrefs = pref;
	        		window.clearTimeout(prefTimeout);
	    	        console.log("Cleared the timeout call..")
	    	        callback();
	        	}
	        });
	    }
		
		if(userId!=null) {
			localStore.setItem = function(i,v) {
				if(userId=='token')
					return;
				console.log("setting to cloud : "+i+"="+v);
				userPrefs.set(i,v);
				userPrefs.save(function(err) {
					if(err) {
						console.log("Prefs not saved in the cloud - "+err);
					}
				});
			}
			localStore.getItem = function(i) {
				console.log("reading from cloud : "+i);
				return userPrefs.get(i);
			}
		} else {
			try {
				var p = window.localStorage;
				localStore.setItem = function(i,v) {
					console.log("setting to localStorage : "+i+"="+v);
					localStorage.setItem(i,v);
				}
				localStore.getItem = function(i) {
					console.log("reading from localStorage : "+i);
					return localStorage.getItem(i);
				}
			} catch(e) {
				console.log("seems to be inside an iframe, Using cookie instead..");
				localStore.setItem = function(i,v) {
					console.log("setting to cookie : "+i+"="+v);
					$.cookie(i, v);
				}
				localStore.getItem = function(i) {
					console.log("reading from cookie : "+i);
					return $.cookie(i);
				}
			}
		}
		
		function gel(id) {
			return $('#'+id);	
		}
		
		$(document).ready(function() {
			var americaStrTickers = "^DJI,^GSPC,^IXIC,^GSPTSE,^MERV,^BVSP,^IPSA,^MXX,";
			var europeStrTickers = "^FTSE,^IETP,^FCHI,^GDAXI,^AEX,^SSMI,^BFX,^ISEQ,^ATX,^STOXX50E,";
			var asiaStrTickers = "^JKSE,^KLSE,^N225,^STI,^KS11,^TWII,^HSI,PSEI.PS,^CSE,^TA100,^AORD,^NZ50";
			var baseURL = "http://finance.yahoo.com/d?s=";
			var refreshrate = 15;
			var sortcol = 'symbol';
			var newDate = new Date().getTime();
			var reloadId = "0";
			var region, showStrength, stockTickers, strTickers, showchart;
			var cURL = "http://ichart.finance.yahoo.com/t?s=";
			var staticImgUrl = new Array();
			function initWidget() {
				region = localStore.getItem("region");			
				showStrength = localStore.getItem("showstrength");
				showchart = localStore.getItem("showchart");
				if(showchart==null)
					showchart = "1";
				if(region==1)
					strTickers = americaStrTickers;
				else if(region==2)
					strTickers = europeStrTickers;
				else if(region==3)
					strTickers = asiaStrTickers;
				else
					strTickers = americaStrTickers+europeStrTickers+asiaStrTickers;
					
				stockTickers = convertToArray(strTickers);
				staticImgUrl = new Array();
				for (var u = 0; u < stockTickers.length; u++) {
					staticImgUrl[getAlphaNumericName(stockTickers[u].symbol)] = "http://udaysasi-gadgets.googlecode.com/svn/trunk/"+getAlphaNumericName(stockTickers[u].symbol)+".gif"; 
				}
				if (showchart == 5) {
				    cURL = "http://ichart.finance.yahoo.com/v?s=";
				}
				else if (showchart == 90) {
				    cURL = "http://ichart.finance.yahoo.com/z?t=3m&l=off&z=b&s=";
				}
				else if (showchart == 180) {
				    cURL = "http://ichart.finance.yahoo.com/z?t=6m&l=off&z=b&s=";
				}
				else if (showchart == 365) {
				    cURL = "http://ichart.finance.yahoo.com/z?t=1y&l=off&z=b&s=";
				}
				var title = localStore.getItem("title");
				if(title!='' && title!="Uday's Global Index Watch")
					title += ' - Global Index Watch';
				
			}
		
			function getAlphaNumericName(txtString)
			{
				txtString = txtString.toLowerCase();
				txtString = txtString.replace(/[^a-zA-Z 0-9]+/g,"");
				return txtString;
			}
			
			showStrengthContent = function() {
				showStrength = localStore.getItem("showstrength");
				if(showStrength==0)
				{
					gel('strengthContent').css('display', '');
					gel('strHorLine').css('display', '');
					showStrength = 1;		
					localStore.setItem("showstrength", 1);
				}
				else
				{
					gel('strengthContent').css('display', 'none');		
					gel('strHorLine').css('display', 'none');		
					showStrength = 0;
					localStore.setItem("showstrength", 0);
				}
			}
			
			function convertToString(arr) {
			    var returnString = "";
			    for (var g = 0; g < arr.length; g++) {
			        returnString += arr[g].symbol + ",";
			    }
			    return returnString;
			}
		
			function convertToString2(arr) {
			    var returnString = "";
			    for (var g = 0; g < arr.length; g++) {
			        returnString += arr[g].symbol + "|" + arr[g].numshares + "|" + arr[g].buyprice + ",";
			    }
			    return returnString;	
			}
		
			function convertToArray(str) {
			    var returnArray = new Array();
			    str = str.replace(/ /g, ",");
			    var ticks = str.split(",");
			    // ticks.sort();
			    for (var d = 0; d < ticks.length; d++) {
			        var curTicker = ticks[d];
			        curTicker = curTicker.toUpperCase();
			        if (curTicker == "") {
			            continue;
			        }
			        returnArray.push(new StockTicker(curTicker, "Loading..", "0", "0", "(0%)"));
			    }
			    return returnArray;
			}
		
			function StockTicker(symbol, name, price, change, percent) {
			    this.symbol = symbol;
			    this.name = name;
			    this.price = price;
			    this.change = change;
			    this.percent = percent;
			}
			function getSymbolArray() {
			    var sa = new Array();
			    for (u = 0; u < stockTickers.length; u++) {
			        sa = sa.concat(stockTickers[u].symbol);
			    }
			    return sa;
			}
			
			function callServer() {
				getDowData();
			    var sa = getSymbolArray();
			    if (sa.length == 0) {
			        return;
			    }
			    var symbol = "";
			    for (var h = 0; h < sa.length - 1; h++) {
			        symbol += sa[h] + ",";
			    }
			    symbol += sa[h];
			    var newDate = new Date().getTime(); 

				customAjax("http://query.yahooapis.com/v1/public/yql?q=select+*+from+csv+where+url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes.csv%3Fs%3D"+encodeURIComponent(encodeURIComponent(symbol))+"%26f%3Dnsl1p2c1'+and+columns%3D'name%2Csymbol%2CLastTradePriceOnly%2CPercentChange%2CChange'&format=json", responseText);
			    
			    try {
			        clearTimeout(reloadId);
			    }
			    catch (e) {
			    }    
				if (refreshrate != -1) {
					reloadId = setTimeout(callServer, refreshrate * 1000);
			    }
			}
			
			function getDowData() {
				var curQuoteTicker = "^DJI";
	            var pos = getPosition(curQuoteTicker);
	            if(pos==-1)
	            	return;  
	            
	            //customAjax("http://query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20google.igoogle.stock%20WHERE%20stock%3D%22.DJI%22&format=json&env=http%3A%2F%2Fdatatables.org%2Falltables.env", dowResponseText);
	            
				$.ajax({
				   type: 'GET',
				    //url: "http://finance.google.com/finance/info?client=ig&q=.DJI",
				    url: "http://quote.cnbc.com/quote-html-webservice/quote.htm?symbols=.DJIA&output=jsonp",
				    async: false,
				    jsonpCallback: 'dowCallback',
				    contentType: "application/json",
				    dataType: 'jsonp',
				    success: function(json) {
				       console.log(json);
				       dowCallback(json);
				    },
				    error: function(e) {
				       console.log("Error getting Dow data : "+e.message);
				    }
				});
			}
			
			/*
			function dowCallback(responseArr) {
				if(!(responseArr && responseArr.length>0))
					return;
				var curQuote = responseArr[0];
	            var curQuoteTicker = curQuote["t"];
	            curQuoteTicker = "^DJI";
	            var pos = getPosition(curQuoteTicker);
	            if(pos==-1)
	            	return;  	
	            
	            symbol = getSymbol(pos);
	            if (symbol == "") {
	                return;
	            }
	            var nameSpan, priceSpan, changeSpan, percentSpan, tickerSpan;
	            var row;
	            
	            nameSpan = gel(getAlphaNumericName(symbol) + "NameSpan");
	            priceSpan = gel(getAlphaNumericName(symbol) + "PriceSpan");
	            changeSpan = gel(getAlphaNumericName(symbol) + "ChangeSpan");
	            percentSpan = gel(getAlphaNumericName(symbol) + "PercentSpan");
	            tickerSpan = gel(getAlphaNumericName(symbol) + "Span");
	            row = gel(getAlphaNumericName(symbol) + "Row");
	            
	            var curQuoteName = "Dow Jones Industrial Average";
	            if (symbol == curQuoteName) {
	                curQuoteName = "Invalid symbol";
	            }
	            curQuoteName = curQuoteName.toUpperCase();
	            if(curQuoteName.length>18)
	            	curQuoteName = curQuoteName.substring(0,18);
	            nameSpan.html(curQuoteName);
	            setName(pos, curQuoteName);
	            var curQuotePrice = removeBold(curQuote["l"]);
	            curQuotePrice = rcs(curQuotePrice);
	            curQuotePrice = removeItalics(curQuotePrice);
	            var curQuoteChange = removeBold(curQuote["c"]);
	            curQuoteChange = removeItalics(curQuoteChange);
	            try {
	                curQuotePrice = parseFloat(curQuotePrice.replace(",",""));
	                if (curQuotePrice > 0.1) {
	                    curQuotePrice = roundNumber(curQuotePrice);
	                    curQuotePrice = round2Decimals(curQuotePrice);
	                }
	            }
	            catch (e) {
	                curQuotePrice = "N/A";
	            }
	            var curQuotePercentChange ="";
	            try {
	            	curQuotePercentChange = curQuote["cp"];
	            }
					catch (e) {
						 curQuotePercentChange = "N/A";
					}
	            curQuotePercentChange = removeBold(curQuotePercentChange);
	            curQuotePercentChange = removeItalics(curQuotePercentChange);
	            curQuotePercentChange = trim(curQuotePercentChange);
	            try {
	                curQuotePercentChange = parseFloat(curQuotePercentChange.replace(",",""));
	                if (curQuotePrice > 0.1) {
	                    curQuotePercentChange = roundNumber(curQuotePercentChange);
	                    curQuotePercentChange = round2Decimals(curQuotePercentChange);
	                }
	            }
	            catch (e) {
	                curQuotePercentChange = "N/A";
	            }
	            priceSpan.html(curQuotePrice);
	            var curQuoteOldPrice = getPrice(pos);
	            setPrice(pos, curQuotePrice);
	            if (isNaN(curQuoteChange)) {
	                curQuoteChange = "N/A";
	            } else {
	                if (curQuotePrice > 0.1) {
	                    curQuoteChange = roundNumber(curQuoteChange);
	                    curQuoteChange = round2Decimals(curQuoteChange);
	                }
	            }
	            setChange(pos, curQuoteChange);
				if (curQuoteChange != 'N/A' && curQuoteChange >= 0) {
					curQuoteChange = "+" + curQuoteChange;
				}
	            changeSpan.html(curQuoteChange);
	            if (isNaN(curQuotePercentChange)) {
	                curQuotePercentChange = "N/A";
	            } else {
	                curQuotePercentChange = roundNumber(curQuotePercentChange);
	                curQuotePercentChange = round2Decimals(curQuotePercentChange);
	                if (curQuotePercentChange >= 0) {
	                    curQuotePercentChange = "+" + curQuotePercentChange;
	                }
	            }
	            
//	            if (curQuotePercentChange < -3) {
//	                n59c++;
//	            } else {
//	                if (curQuotePercentChange < -1) {
//	                    n25c++;
//	                } else {
//	                    if (curQuotePercentChange < 0) {
//	                        n02c++;
//	                    } else {
//	                        if (curQuotePercentChange > 3) {
//	                            p59c++;
//	                        } else {
//	                            if (curQuotePercentChange > 1) {
//	                                p25c++;
//	                            } else {
//	                                p02c++;
//	                            }
//	                        }
//	                    }
//	                }
//	            }
	            
	            setPercentChange(pos, curQuotePercentChange);
	            percentSpan.html("(" + curQuotePercentChange + "%)");
	            if (parseFloat(curQuotePercentChange.replace(",","")) < 0 || parseFloat(curQuoteChange.replace(",","")) < 0) {
	                changeSpan.css('color', '#990000');
	                percentSpan.css('color', '#990000');
	            } else if (parseFloat(curQuotePercentChange.replace(",","")) > 0 || parseFloat(curQuoteChange.replace(",","")) > 0) {
	                changeSpan.css('color', '#009900');
	                percentSpan.css('color', '#009900');
	            } else {
	                changeSpan.css('color', '#666666');
	                percentSpan.css('color', '#666666');
	            }
			}
			*/
			
			
			function dowCallback(responseData) {
				//console.log(responseData);
				if(!(responseData && responseData["QuickQuoteResult"] && responseData["QuickQuoteResult"]["QuickQuote"]))
					return;
				var curQuote = responseData["QuickQuoteResult"]["QuickQuote"];
	            var curQuoteTicker = curQuote["shortName"];
	            curQuoteTicker = "^DJI";
	            var pos = getPosition(curQuoteTicker);
	            if(pos==-1)
	            	return;  	
	            
	            symbol = getSymbol(pos);
	            if (symbol == "") {
	                return;
	            }
	            var nameSpan, priceSpan, changeSpan, percentSpan, tickerSpan;
	            var row;
	            
	            nameSpan = gel(getAlphaNumericName(symbol) + "NameSpan");
	            priceSpan = gel(getAlphaNumericName(symbol) + "PriceSpan");
	            changeSpan = gel(getAlphaNumericName(symbol) + "ChangeSpan");
	            percentSpan = gel(getAlphaNumericName(symbol) + "PercentSpan");
	            tickerSpan = gel(getAlphaNumericName(symbol) + "Span");
	            row = gel(getAlphaNumericName(symbol) + "Row");
	            
	            var curQuoteName = "Dow Jones Industrial Average";
	            if (symbol == curQuoteName) {
	                curQuoteName = "Invalid symbol";
	            }
	            curQuoteName = curQuoteName.toUpperCase();
	            if(curQuoteName.length>18)
	            	curQuoteName = curQuoteName.substring(0,18);
	            nameSpan.html(curQuoteName);
	            setName(pos, curQuoteName);
	            var curQuotePrice = removeBold(curQuote["last"]);
	            curQuotePrice = rcs(curQuotePrice);
	            curQuotePrice = removeItalics(curQuotePrice);
	            var curQuoteChange = removeBold(curQuote["change"]);
	            curQuoteChange = removeItalics(curQuoteChange);
	            try {
	                curQuotePrice = parseFloat(curQuotePrice.replace(",",""));
	                if (curQuotePrice > 0.1) {
	                    curQuotePrice = roundNumber(curQuotePrice);
	                    curQuotePrice = round2Decimals(curQuotePrice);
	                }
	            }
	            catch (e) {
	                curQuotePrice = "N/A";
	            }
	            var curQuotePercentChange ="";
	            try {
	            	curQuotePercentChange = curQuote["change_pct"];
	            }
					catch (e) {
						 curQuotePercentChange = "N/A";
					}
	            curQuotePercentChange = removeBold(curQuotePercentChange);
	            curQuotePercentChange = removeItalics(curQuotePercentChange);
	            curQuotePercentChange = trim(curQuotePercentChange);
	            try {
	                curQuotePercentChange = parseFloat(curQuotePercentChange.replace(",",""));
	                if (curQuotePrice > 0.1) {
	                    curQuotePercentChange = roundNumber(curQuotePercentChange);
	                    curQuotePercentChange = round2Decimals(curQuotePercentChange);
	                }
	            }
	            catch (e) {
	                curQuotePercentChange = "N/A";
	            }
	            priceSpan.html(curQuotePrice);
	            var curQuoteOldPrice = getPrice(pos);
	            setPrice(pos, curQuotePrice);
	            if (isNaN(curQuoteChange)) {
	                curQuoteChange = "N/A";
	            } else {
	                if (curQuotePrice > 0.1) {
	                    curQuoteChange = roundNumber(curQuoteChange);
	                    curQuoteChange = round2Decimals(curQuoteChange);
	                }
	            }
	            setChange(pos, curQuoteChange);
				if (curQuoteChange != 'N/A' && curQuoteChange >= 0) {
					curQuoteChange = "+" + curQuoteChange;
				}
	            changeSpan.html(curQuoteChange);
	            if (isNaN(curQuotePercentChange)) {
	                curQuotePercentChange = "N/A";
	            } else {
	                curQuotePercentChange = roundNumber(curQuotePercentChange);
	                curQuotePercentChange = round2Decimals(curQuotePercentChange);
	                if (curQuotePercentChange >= 0) {
	                    curQuotePercentChange = "+" + curQuotePercentChange;
	                }
	            }
	            /*
	            if (curQuotePercentChange < -3) {
	                n59c++;
	            } else {
	                if (curQuotePercentChange < -1) {
	                    n25c++;
	                } else {
	                    if (curQuotePercentChange < 0) {
	                        n02c++;
	                    } else {
	                        if (curQuotePercentChange > 3) {
	                            p59c++;
	                        } else {
	                            if (curQuotePercentChange > 1) {
	                                p25c++;
	                            } else {
	                                p02c++;
	                            }
	                        }
	                    }
	                }
	            }
	            */
	            setPercentChange(pos, curQuotePercentChange);
	            percentSpan.html("(" + curQuotePercentChange + "%)");
	            if (parseFloat(curQuotePercentChange.replace(",","")) < 0 || parseFloat(curQuoteChange.replace(",","")) < 0) {
	                changeSpan.css('color', '#990000');
	                percentSpan.css('color', '#990000');
	            } else if (parseFloat(curQuotePercentChange.replace(",","")) > 0 || parseFloat(curQuoteChange.replace(",","")) > 0) {
	                changeSpan.css('color', '#009900');
	                percentSpan.css('color', '#009900');
	            } else {
	                changeSpan.css('color', '#666666');
	                percentSpan.css('color', '#666666');
	            }
			}
			
			
			function dowResponseText(responseString) {
				if(!(responseString && responseString.xml_api_reply && responseString.xml_api_reply.finance))
					return;
				var curQuote = responseString.xml_api_reply.finance;
	            var curQuoteTicker = curQuote["symbol"]["data"];
	            curQuoteTicker = "^DJI";
	            var pos = getPosition(curQuoteTicker);
	            if(pos==-1)
	            	return;  	
	            
	            symbol = getSymbol(pos);
	            if (symbol == "") {
	                return;
	            }
	            var nameSpan, priceSpan, changeSpan, percentSpan, tickerSpan;
	            var row;
	            
	            nameSpan = gel(getAlphaNumericName(symbol) + "NameSpan");
	            priceSpan = gel(getAlphaNumericName(symbol) + "PriceSpan");
	            changeSpan = gel(getAlphaNumericName(symbol) + "ChangeSpan");
	            percentSpan = gel(getAlphaNumericName(symbol) + "PercentSpan");
	            tickerSpan = gel(getAlphaNumericName(symbol) + "Span");
	            row = gel(getAlphaNumericName(symbol) + "Row");
	            
	            var curQuoteName = curQuote["company"]["data"]
	            if (symbol == curQuoteName) {
	                curQuoteName = "Invalid symbol";
	            }
	            curQuoteName = curQuoteName.toUpperCase();
	            if(curQuoteName.length>18)
	            	curQuoteName = curQuoteName.substring(0,18);
	            nameSpan.html(curQuoteName);
	            setName(pos, curQuoteName);
	            var curQuotePrice = removeBold(curQuote["last"]["data"]);
	            curQuotePrice = rcs(curQuotePrice);
	            curQuotePrice = removeItalics(curQuotePrice);
	            var curQuoteChange = removeBold(curQuote["change"]["data"]);
	            curQuoteChange = removeItalics(curQuoteChange);
	            try {
	                curQuotePrice = parseFloat(curQuotePrice);
	                if (curQuotePrice > 0.1) {
	                    curQuotePrice = roundNumber(curQuotePrice);
	                    curQuotePrice = round2Decimals(curQuotePrice);
	                }
	            }
	            catch (e) {
	                curQuotePrice = "N/A";
	            }
	            var curQuotePercentChange ="";
	            try {
	            	curQuotePercentChange = curQuote["perc_change"]["data"];
	            }
					catch (e) {
						 curQuotePercentChange = "N/A";
					}
	            curQuotePercentChange = removeBold(curQuotePercentChange);
	            curQuotePercentChange = removeItalics(curQuotePercentChange);
	            curQuotePercentChange = trim(curQuotePercentChange);
	            try {
	                curQuotePercentChange = parseFloat(curQuotePercentChange);
	                if (curQuotePrice > 0.1) {
	                    curQuotePercentChange = roundNumber(curQuotePercentChange);
	                    curQuotePercentChange = round2Decimals(curQuotePercentChange);
	                }
	            }
	            catch (e) {
	                curQuotePercentChange = "N/A";
	            }
	            priceSpan.html(curQuotePrice);
	            var curQuoteOldPrice = getPrice(pos);
	            setPrice(pos, curQuotePrice);
	            if (isNaN(curQuoteChange)) {
	                curQuoteChange = "N/A";
	            } else {
	                if (curQuotePrice > 0.1) {
	                    curQuoteChange = roundNumber(curQuoteChange);
	                    curQuoteChange = round2Decimals(curQuoteChange);
	                }
	            }
	            setChange(pos, curQuoteChange);
				if (curQuoteChange != 'N/A' && curQuoteChange >= 0) {
					curQuoteChange = "+" + curQuoteChange;
				}
	            changeSpan.html(curQuoteChange);
	            if (isNaN(curQuotePercentChange)) {
	                curQuotePercentChange = "N/A";
	            } else {
	                curQuotePercentChange = roundNumber(curQuotePercentChange);
	                curQuotePercentChange = round2Decimals(curQuotePercentChange);
	                if (curQuotePercentChange >= 0) {
	                    curQuotePercentChange = "+" + curQuotePercentChange;
	                }
	            }
	            /*
	            if (curQuotePercentChange < -3) {
	                n59c++;
	            } else {
	                if (curQuotePercentChange < -1) {
	                    n25c++;
	                } else {
	                    if (curQuotePercentChange < 0) {
	                        n02c++;
	                    } else {
	                        if (curQuotePercentChange > 3) {
	                            p59c++;
	                        } else {
	                            if (curQuotePercentChange > 1) {
	                                p25c++;
	                            } else {
	                                p02c++;
	                            }
	                        }
	                    }
	                }
	            }
	            */
	            setPercentChange(pos, curQuotePercentChange);
	            percentSpan.html("(" + curQuotePercentChange + "%)");
	            if (parseFloat(curQuotePercentChange) < 0 || parseFloat(curQuoteChange) < 0) {
	                changeSpan.css('color', '#990000');
	                percentSpan.css('color', '#990000');
	            } else if (parseFloat(curQuotePercentChange) > 0 || parseFloat(curQuoteChange) > 0) {
	                changeSpan.css('color', '#009900');
	                percentSpan.css('color', '#009900');
	            } else {
	                changeSpan.css('color', '#666666');
	                percentSpan.css('color', '#666666');
	            }
			}
			
			function customAjax(myurl, callback) {
				$.ajax({
			        type: "GET",
			        url: myurl,
			        dataType: "json",
			        success: function(data) {
						callback(data.query.results);
			        }
			    });
			}
			
			function responseText(responseString) {
				refreshrate = 60;
				console.log(responseString);
			    var result = responseString.row;
			    var symbol;
			    try {
			        var quotes = new Array();
			        quotes.push(result);
			    	if($.isArray(result)) {
			    		quotes = result;
			    	}
			        var n59p = 0, n25p = 0, n02p = 0, p25p = 0, p02p = 0, p59p = 0;
			        var n59c = 0, n25c = 0, n02c = 0, p25c = 0, p02c = 0, p59c = 0;
			        for (var c = 0; c < quotes.length; c++) {
		
				    	var curQuote = quotes[c];
			            var curQuoteTicker = curQuote["symbol"];
			            var pos = getPosition(curQuoteTicker);
			            if(pos==-1)
			            	continue;            	
			            
			            symbol = getSymbol(pos);
			            if (symbol == "") {
			                continue;
			            }
			            var nameSpan, priceSpan, changeSpan, percentSpan, tickerSpan;
			            var row;
			            
			            nameSpan = gel(getAlphaNumericName(symbol) + "NameSpan");
			            priceSpan = gel(getAlphaNumericName(symbol) + "PriceSpan");
			            changeSpan = gel(getAlphaNumericName(symbol) + "ChangeSpan");
			            percentSpan = gel(getAlphaNumericName(symbol) + "PercentSpan");
			            tickerSpan = gel(getAlphaNumericName(symbol) + "Span");
			            row = gel(getAlphaNumericName(symbol) + "Row");
			            
			            var curQuoteName = curQuote["name"]
			            if (symbol == curQuoteName) {
			                curQuoteName = "Invalid symbol";
			            }
			            curQuoteName = curQuoteName.toUpperCase();
			            nameSpan.html(curQuoteName);
			            setName(pos, curQuoteName);
			            var curQuotePrice = removeBold(curQuote["LastTradePriceOnly"]);
			            curQuotePrice = rcs(curQuotePrice);
			            curQuotePrice = removeItalics(curQuotePrice);
			            var curQuoteChange = removeBold(curQuote["Change"]);
			            curQuoteChange = removeItalics(curQuoteChange);
			            try {
			                curQuotePrice = parseFloat(curQuotePrice);
			                if (curQuotePrice > 0.1) {
			                    curQuotePrice = roundNumber(curQuotePrice);
			                    curQuotePrice = round2Decimals(curQuotePrice);
			                }
			            }
			            catch (e) {
			                curQuotePrice = "N/A";
			            }
			            var curQuotePercentChange ="";
			            try {
			            	curQuotePercentChange = curQuote["PercentChange"];;
			            }
							catch (e) {
								 curQuotePercentChange = "N/A";
							}
			            curQuotePercentChange = removeBold(curQuotePercentChange);
			            curQuotePercentChange = removeItalics(curQuotePercentChange);
			            curQuotePercentChange = trim(curQuotePercentChange);
			            try {
			                curQuotePercentChange = parseFloat(curQuotePercentChange);
			                if (curQuotePrice > 0.1) {
			                    curQuotePercentChange = roundNumber(curQuotePercentChange);
			                    curQuotePercentChange = round2Decimals(curQuotePercentChange);
			                }
			            }
			            catch (e) {
			                curQuotePercentChange = "N/A";
			            }
			            priceSpan.html(curQuotePrice);
			            var curQuoteOldPrice = getPrice(pos);
			            setPrice(pos, curQuotePrice);
			            if (isNaN(curQuoteChange)) {
			                curQuoteChange = "N/A";
			            } else {
			                if (curQuotePrice > 0.1) {
			                    curQuoteChange = roundNumber(curQuoteChange);
			                    curQuoteChange = round2Decimals(curQuoteChange);
			                }
			            }
			            setChange(pos, curQuoteChange);
						if (curQuoteChange != 'N/A' && curQuoteChange >= 0) {
							curQuoteChange = "+" + curQuoteChange;
						}
			            changeSpan.html(curQuoteChange);
			            if (isNaN(curQuotePercentChange)) {
			                curQuotePercentChange = "N/A";
			            } else {
			                curQuotePercentChange = roundNumber(curQuotePercentChange);
			                curQuotePercentChange = round2Decimals(curQuotePercentChange);
			                if (curQuotePercentChange >= 0) {
			                    curQuotePercentChange = "+" + curQuotePercentChange;
			                }
			            }
			            if (curQuotePercentChange < -3) {
			                n59c++;
			            } else {
			                if (curQuotePercentChange < -1) {
			                    n25c++;
			                } else {
			                    if (curQuotePercentChange < 0) {
			                        n02c++;
			                    } else {
			                        if (curQuotePercentChange > 3) {
			                            p59c++;
			                        } else {
			                            if (curQuotePercentChange > 1) {
			                                p25c++;
			                            } else {
			                                p02c++;
			                            }
			                        }
			                    }
			                }
			            }
			            setPercentChange(pos, curQuotePercentChange);
			            percentSpan.html("(" + curQuotePercentChange + "%)");
			            if (parseFloat(curQuotePercentChange) < 0 || parseFloat(curQuoteChange) < 0) {
			                changeSpan.css('color', '#990000');
			                percentSpan.css('color', '#990000');
			            } else if (parseFloat(curQuotePercentChange) > 0 || parseFloat(curQuoteChange) > 0) {
			                changeSpan.css('color', '#009900');
			                percentSpan.css('color', '#009900');
			            } else {
			                changeSpan.css('color', '#666666');
			                percentSpan.css('color', '#666666');
			            }
			        }
			        var total = n59c + n25c + n02c + p02c + p25c + p59c;
			        n59p = roundNumber(n59c * 100 / total);
			        n25p = roundNumber(n25c * 100 / total);
			        n02p = roundNumber(n02c * 100 / total);
			        p02p = roundNumber(p02c * 100 / total);
			        p25p = roundNumber(p25c * 100 / total);
			        p59p = roundNumber(p59c * 100 / total);
			        gel("n59").css('width', n59p + "%");
			        gel("n59").attr({title : n59c+" of "+total+" indices down over 3%"});
			        gel("n25").css('width', n25p + "%");
			        gel("n25").attr({title : n25c+" of "+total+" indices down between 1% and 3%"});
			        gel("n02").css('width', n02p + "%");
			        gel("n02").attr({title : n02c+" of "+total+" indices down between 0% and 1%"});
			        gel("p02").css('width', p02p + "%");
			        gel("p02").attr({title : p02c+" of "+total+" indices up between 0% and 1%"});
			        gel("p25").css('width', p25p + "%");
			        gel("p25").attr({title : p25c+" of "+total+" indices up between 1% and 3%"});
			        gel("p59").css('width', p59p + "%");
			        gel("p59").attr({title : p59c+" of "+total+" indices up over 3%"});
			    }
			    catch (e) {
			    	console.log(e + "Symbol : "+symbol);
			    }
			}
			
			function fixCommas(str) {
			    var x = 0;
			    while (str.indexOf("\"", x) >= 0) {
			        var y = str.indexOf("\"", x);
			        var z = str.indexOf("\"", y + 1);
			        var w = str.indexOf(",", y);
			        if (w > y && w < z) {
			            str = str.substring(0, w) + "." + str.substring(w + 1);
			        }
			        x = z + 1;
			    }
			    return str;
			}
			
			function getPrice(c) {
			    return stockTickers[c].price;
			}
			function setPrice(c, newPrice) {
			    stockTickers[c].price = newPrice;
			}
			function setPercentChange(c, newPercent) {
			    stockTickers[c].percent = newPercent;
			}
			function setChange(c, newChange) {
			    stockTickers[c].change = newChange;
			}
			function getSymbol(c) {
			    if (c < stockTickers.length) {
			        return stockTickers[c].symbol;
			    } else {
			        return "";
			    }
			}
			function setName(c, newName) {
			    stockTickers[c].name = newName;
			}
			function getRefinedSymbol(str) {
			    return str.substring(1, str.length - 1);
			}
			function getRefinedName(str) {
			    return str.substring(1, str.length - 1);
			}
			function trim(str) {
			    return str.replace(/^\s*|\s*$/g, "");
			}
			
			function paintStockTicker() {
				initWidget();
				//widget.log('paintStockTicker');
				gel('contentData').html('Portfolios will load here...');
				 
				var hideCols = localStore.getItem("hidecols");
				var changedisplay="", percentdisplay="";
				if(hideCols==1)
					changedisplay = "none";
				if(hideCols==2)
					percentdisplay = "none";	
					
			    var header = "<table class=\"table table-condensed table-striped\" align=center style=\"table-layout: fixed; border:0;  font-family: arial,sans-serif;\" width=\"100%\" id=\"contentTable\" cellspacing=0 cellpadding=1>";
			    var footer = "</table>";
			    var contentText = "";
			    var bgcolor="ffffff";
			    for (i = 0; i < stockTickers.length; i++) {
			    	if(i%2==1) 
			    		bgcolor="ffffff";	
			    	else
			    		bgcolor="f5f5f5";
			   	    		
			        contentText += "<tr id=\"" + stockTickers[i].symbol + "Row\" onMouseOver=\"showChart('" + stockTickers[i].symbol + "')\"  bgcolor=\""+bgcolor+"\" >";
			        contentText += "<td width=\"5%\" style=\"padding-right: 3px;width:20px\" align=\"center\"><img src=\""+staticImgUrl[getAlphaNumericName(stockTickers[i].symbol)]+"\" width=\"21\" height=\"14\" border=\"1\"/></td>";
			        contentText += "<td width=\"35%\" class=\"dynamic\" nowrap style=\"display:\" align=\"left\"><font size=\"-1\"><a class=\"link\" href=\"http://finance.yahoo.com/q?s=" + stockTickers[i].symbol + "\" target=\"blank\"><span rel=\"popover\" style=\"display:\" id=\"" + getAlphaNumericName(stockTickers[i].symbol) + "NameSpan\">" + stockTickers[i].name + "</span></a></font></td>";
			        contentText += "<td width=\"20%\" style=\"padding-right: 0.5em;\" align=\"right\"><font size=\"-1\"><span id=\"" + getAlphaNumericName(stockTickers[i].symbol) + "PriceSpan\">" + stockTickers[i].price + "</span></font></td>";
			        contentText += "<td width=\"15%\" style=\"display:"+changedisplay+";padding-right: 0.5em;\" align=\"right\" nowrap><font size=\"-1\"><span id=\"" + getAlphaNumericName(stockTickers[i].symbol) + "ChangeSpan\">" + stockTickers[i].change + "</span></font></td>";
			        contentText += "<td width=\"15%\" align=\"right\" style=\"display:"+percentdisplay+"\" nowrap><font size=\"-1\"><span id=\"" + getAlphaNumericName(stockTickers[i].symbol) + "PercentSpan\">" + stockTickers[i].percent + "</span></font></td>";
			        contentText += "</tr>";
			    }    
			    gel("contentData").html(header + contentText + footer);
			    $("td[align='right']").css("text-align", "right");
			    try {
			        clearTimeout(reloadId);
			    }
			    catch (e) {
			    }
			    callServer();
			}
		
			showChart = function (sym) {
			    if (showchart == 0) {
			        return;
			    }
			    
			    var img = "<img src='" + cURL + sym + "'/>";
			    gel(getAlphaNumericName(sym) + "NameSpan").popover({'title':'', 'content': img, 'trigger':'hover', 'html': true});
			}
			
			function roundNumber(num) {
			    var rlength = 2;
			    var newnumber = Math.round(num * Math.pow(10, rlength)) / Math.pow(10, rlength);
			    return newnumber;
			}
		
			function formatData(str) {
			    str = str.replace("\n", "").replace("\r", "");
			    if (str.indexOf("\"") == -1) {
			        return str;
			    } else {
			        return str.substring(1, str.length - 1);
			    }
			}
			function round2Decimals(n) {
			    var stringNumber = "" + n;
			    if (stringNumber.indexOf(".") == -1) {
			        stringNumber += ".00";
			    } else {
			        if (stringNumber.substring(stringNumber.indexOf(".") + 1).length == 1) {
			            stringNumber += "0";
			        }
			    }
			    return stringNumber;
			}
			function sortArray(arr) {
			    if (arr.length == 0) {
			        return arr;
			    }
			    var newArray = new Array();
			    var stA = new Array();
			    for (var l = 0; l < arr.length; l++) {
			        stA.push(arr[l].symbol);
			    }
			    stA.sort();
			    for (var h = 0; h < stA.length; h++) {
			        for (var o = 0; o < arr.length; o++) {
			            if (stA[h] == arr[o].symbol) {
			                newArray.push(arr[o]);
			            }
			        }
			    }
			    return newArray;
			}
		
			function sortArray2(tickcopy, col) {
				sortcol = col;	
				var exp = 'tickers[l].'+col;
				var tickers = new Array();
				var nA = new Array();
				var stA = new Array();	
				for(k=0;k<tickcopy.length;k++)
					tickers.push(tickcopy[k]);
		
				for (var l = 0; l < tickers.length; l++) {
					if(parseFloat(eval(exp)))
						stA.push(parseFloat(eval(exp)));
			    	else
			    		stA.push(eval(exp));
				}
				if(col=='price' || col=='change' || col=='percent')
				{
					try{
			    		stA.sort(sortNumber);
			    	}catch(e) {
			    		stA.sort();
			    	}
			    }
			    else
			    	stA.sort();
		
			    for (var h = 0; h < stA.length; h++) {
			    	for (var l = 0; l < tickers.length; l++) {
			        	if(nA.contains(tickers[l]))
			        		continue;
			        
			        	if(parseFloat(stA[h]))
			        	{
							if (parseFloat(stA[h]) == parseFloat(eval(exp))) {					
									nA.push(tickers[l]);
							}
						}
						else
						{
							if (stA[h] == eval(exp)) {
								nA.push(tickers[l]);
							}
						}
			        }
			    }
		
				tickers = nA;
		
				return tickers;
			}
			function sortNumber(a,b)
			{
				if(a-b)
					return a-b;
				else
					return true;
			}
			function sortByColumn(col)
			{
				stockTickers = sortArray2(stockTickers, col);
				paintStockTicker();
			}
		
			function removeBold(str) {
			    var boldIndexStart = str.indexOf("<b>");
			    var boldIndexEnd = str.lastIndexOf("</b>");
			    if (boldIndexStart == -1) {
			        return str;
			    }
			    var curQuotePrice = str.substring(boldIndexStart + 3, boldIndexEnd);
			    return curQuotePrice;
			}
			function removeItalics(str) {
			    var italicIndexStart = str.indexOf("<i>");
			    var italicIndexEnd = str.lastIndexOf("</i>");
			    if (italicIndexStart == -1) {
			        return str;
			    }
			    var curQuotePrice = str.substring(italicIndexStart + 3, italicIndexEnd);
			    return curQuotePrice;
			}
			function rcs(str) {
				var imgstart = str.indexOf("<img");
			    if (imgstart == -1) {
			        return str;
			    }	
			    var csis = str.indexOf(">", imgstart);
			    var curQuotePrice = str.substring(0,imgstart)+str.substring(csis + 1);
			    return curQuotePrice;
			}
			function joinString(a, b) {
			    var onelen = a.length;
			    var twolen = (a.length + b.length > 20) ? (20 - a.length) : b.length;
			    if (twolen != b.length) {
			        b = b.substring(0, twolen) + "..";
			    }
			    var res = b + " (" + a + ")";
			    return res;
			}
			Array.prototype.contains = function(element)   {
				for (var i = 0; i < this.length; i++)
					if (this[i] == element)
						return true;
				return false;
			}
		
			function getPosition(sym) {
				var pos = 0;
				var arr = stockTickers;
				for(var l = 0; l < arr.length; l++) {
					if(arr[l].symbol.toUpperCase()==sym.toUpperCase())
						return (l);
				}
				return -1;
			}
		
			function log(str) {
			  // gel("logDiv").innerHTML += str;
			}
			
			function loadSettings() {
				$("#inputHidecols > select").val(localStore.getItem("hidecols"));
				$("#inputRegion > select").val(localStore.getItem("region"));
				$("#inputShowCharts > select").val(localStore.getItem("showchart"));
				//console.log("loading settings from storage");
			}
			
			function saveSettings() {
				localStore.setItem("hidecols", $("#inputHidecols > select").val());
				localStore.setItem("region", $("#inputRegion > select").val());
				localStore.setItem("showchart", $("#inputShowCharts > select").val());
				//console.log("saved settings to storage");
				initWidget();
				paintStockTicker();
			}
			
			if(userId==null) {
				initWidget();
				paintStockTicker();
			} else {
				getUserPrefs(function() {
					initWidget();
					paintStockTicker();
				});
				$("#fullscreen").attr("href", "http://udaysasi-gadgets.googlecode.com/svn/trunk/globalIndexWatch.html?subscriptionid="+userId);
			}
			 
			$("#strengthbtn").click(showStrengthContent);
			$("#settingsloadbtn").click(loadSettings);
			$("#settingssavebtn").click(saveSettings);
		});
		

	</script>

</body>
</html>